<template>
  <div class="Details_content" v-if="content">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/post">旅游攻略</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>攻略详情</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="main">
      <!-- 文章标题 -->
      <h1>{{content.title}}</h1>
      <!-- 文章发布时间个阅读量 -->
      <div class="post_info">
        <a href="//travel.qunar.com/space/160623159@qunar">
          <img :src="$axios.defaults.baseURL+content.account.defaultAvatar" alt />
          {{content.account.nickname}}
        </a>
        发布于：{{content.city.created_at}}&nbsp;&nbsp;&nbsp;
        阅读：{{content.watch || 0}}
      </div>
      <!-- 文章详情 -->
      <div class="post_content" v-html="content.content"></div>
      <!-- 文章分享功能 -->
      <div class="post_crtl">
        <div class="post_crtl_item">
          <span class="iconfont iconpinglun" @click="dia"></span>
          <p>评论({{content.comments.length}})</p>
        </div>
        <div class="post_crtl_item" @click="share">
          <span class="iconfont iconfenxiang"></span>
          <p>分享</p>
        </div>
      </div>
      <!-- 评论区域 -->
      <div class="cmt_wrapper">
        <h4 class="cmt_title" id="pinlun">评论</h4>
        <div class="cmt_reply_textarea">
          <el-tag
            v-if="closetag"
            :closable="true"
            type="info"
            :disable-transitions="false"
            @close="handleClose"
          >回复@{{nickname}}</el-tag>
          <!-- 评论内容输入框 -->
          <div class="cmt_input">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请输入内容"
              v-model="textarea2"
              ref="shuai"
            ></el-input>
          </div>
          <!-- 图片上传和提交按钮 -->
          <div class="cmt_input_ctrls">
            <!-- 文件上传组件 -->
            <!-- name属性是上传的文件字段默认为file -->
            <div class="cmt_pics">
              <el-upload
                :action="$axios.defaults.baseURL+'/upload'"
                name="files"
                list-type="picture-card"
                :file-list="fileList"
                :auto-upload="true"
                :on-success="handleAvatarSuccess"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <el-avatar shape="square" :src="file.url"></el-avatar>
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img height="100%" :src="dialogImageUrl" alt />
              </el-dialog>
            </div>
            <!-- 点击上传按钮 -->
            <div class="btn">
              <el-button type="primary" size="mini" @click="handleClick">提交</el-button>
            </div>
          </div>
          <div class="cmt_reply_noUser" v-if="showthistable">
            <span>
              请
              <a href="JavaScript:;" @click="tologinPage">登录</a>后评论
            </span>
          </div>
        </div>

        <!-- 评论展示区域 -->
        <div class="cmt_list">
          <div v-if="total">
            <Comment :commentData="commentData" :total="total" @callReply="callReply" />
          </div>
          <div class="cmt_empty" v-else>暂无评论，赶紧抢占沙发</div>
        </div>
        <!-- 分页组件 -->
        <div class="page" v-if="this.total">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-sizes="pageData.pagesizes"
            :page-size="pageData.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="this.total"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      content: null,
      textarea2: "",
      // 图片上传后接受的数据
      fileUpload: [],
      // 默认评论获取的数据条数
      fileList: [],
      data: {
        limit: 3,
        start: 0,
      },
      followId: "",
      commentData: [],
      total: 0,
      // 分页组件数据
      pageData: {
        pagesize: 3, //页容量
        pagesizes: [3, 4, 5, 6], //每页显示选择器的选项
      },
      currentPage: 1, //当前页
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      closetag: false,
      nickname: "",
      showthistable: false,
    };
  },
  watch: {
    $route(to, from) {
      this.$axios.get("/posts?id=" + this.$route.query.id).then((res) => {
        this.content = res.data.data[0];
        this.getComment(this.data);
      });
      // console.log(res);
    },
  },

  mounted() {
    this.getPost();
    const a = this.$store.state.callreplay.replayName;
    const b = this.$store.state.callreplay.replayId;
    if (a && b) {
      this.followId = b;
      this.nickname = a;
      this.closetag = true;
    }
  },
  methods: {
    // 去登录界面
    tologinPage() {
      if (!this.$store.state.user.token) {
        this.$message.warning("正在去登录");
        // 获取当前页面的url  完整
        const { fullPath } = this.$route;
        // 将url 设置进  vuex中
        this.$store.commit("page/setSourceURL", fullPath);
        setTimeout(() => {
          this.$router.replace("/user/login").catch((err) => {
            console.log(err);
          });
        }, 500);
      }
    },
    // 点击页面评论图标按钮时聚焦到input输入框
    dia() {
      if (this.$refs.shuai) {
        this.$refs.shuai.focus();
      }
    },
    share() {
      this.$message.closeAll();
      this.$message("暂无此功能");
    },
    async getPost() {
      //   获取文章id
      const { id } = this.$route.query;
      // 发送请求
      const res = await this.$axios.get("/posts?id=" + id);
      // console.log(res);
      this.content = res.data.data[0];
      // console.log(this.content);
      // 解决返回的标签图片大小乱搞的
      // this.$nextTick(() => {
      //   document.querySelectorAll("img").forEach((v, i) => {
      //     v.style.maxWidth = "700px";
      //   });
      // });
      this.getComment(this.data);
    },
    handleClose() {
      this.closetag = false;
      this.followId = "";
    },
    // 获取评论数据
    async getComment(data) {
      if (this.content) {
        const res = await this.$axios.get("/posts/comments", {
          params: {
            post: this.content.id,
            _limit: data.limit,
            _start: data.start,
          },
        });
        // console.log(res);
        this.commentData = res.data.data;
        this.total = res.data.total;
      }
    },
    //上传图片成功之后的回调
    handleAvatarSuccess(response, file, fileList) {
      // 将图片url保存到本组件
      this.fileUpload = response;
      // console.log(this.fileUpload);
    },
    callReply(parentId, nickname) {
      this.followId = parentId;
      // console.log(parentId);
      this.closetag = true;
      this.nickname = nickname;
      //  如果没有token点击的时候就要进行状态保持，接受的用户名和ID储存到本地
      if (!this.$store.state.user.token) {
        const callReplyState = {
          followId: this.followId,
          nickName: this.nickname,
        };
        this.$store.commit("callreplay/keepState", callReplyState);
      }
      if (this.$refs.shuai) {
        this.$refs.shuai.focus();
      } else {
        this.$message.closeAll();
        this.$message("请先登录");
        const cmt = this.$el.querySelector(".cmt_wrapper");
        this.$nextTick(() => {
          document.querySelector("html").scrollTop = cmt.offsetTop;
        });
      }
    },
    //提交评论
    async handleClick() {
      //提交评论时，将上传文件夹清空
      this.fileList = [];
      this.$message.closeAll();
      // 点击评论按钮先判读本地是否存在token值
      // 如果没有登录就先跳转到登录页
      if (!this.$store.state.user.token) {
        this.$message.error("请先登录");
        this.showthistable = true;
        // // 获取当前页面的url  完整
        // const { fullPath } = this.$route;
        // // 将url 设置进  vuex中
        // this.$store.commit("page/setSourceURL", fullPath);
        // setTimeout(() => {
        //   this.$router.replace("/user/login").catch((err) => {
        //     console.log(err);
        //   });
        // }, 500);
      } else {
        if (!this.textarea2 && !this.fileUpload.length) {
          this.$message("请输入内容");
          return;
        }

        const data = {
          content: this.textarea2, //评论内容对象
          pics: this.fileUpload, //图片数组
          post: this.$route.query.id, //文章id
        };
        if (this.followId) {
          data.follow = this.followId;
        }
        // console.log(data);
        const res = await this.$axios.post("/comments", data, {
          headers: {
            // "Content-Type": "application / json",
            Authorization: "Bearer " + this.$store.state.user.token,
          },
        });
        // console.log(res);
        this.getComment(this.data);
        //清空输入框内容
        this.textarea2 = "";
        // 关闭之前的提示框
        this.$message.closeAll();
        this.$message.success("评论成功");
        // 清空本地数据
        this.$store.commit("callreplay/clearState");
        this.handleClose();
        this.getPost();
      }
    },
    //上传组件内点击删除按钮
    handleRemove(file) {
      // console.log(file);
      // 点击删除按钮，将储存文件的数组清空
      this.fileList = [];
    },
    //上传组件内点击放大按钮
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSizeChange(val) {
      // 改变页容量时触发的事件
      // console.log(val);
      this.data.start = 0;
      this.data.limit = val;
      this.currentPage = 1;
      this.getComment(this.data);
      const cmt = this.$el.querySelector(".cmt_wrapper");
      this.$nextTick(() => {
        document.querySelector("html").scrollTop = cmt.offsetTop;
      });
    },
    handleCurrentChange(val) {
      // 改变当前页触发的事件
      // console.log(val);
      this.data.start = (val - 1) * this.pageData.pagesize;
      this.getComment(this.data);
      const cmt = this.$el.querySelector(".cmt_wrapper");
      this.$nextTick(() => {
        document.querySelector("html").scrollTop = cmt.offsetTop;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.Details_content {
  .main {
    // 页面文章标题
    h1 {
      padding: 20px 0;
      border-bottom: 1px solid #ddd;
    }
    // 文章发布时间和浏览量
    .post_info {
      color: #999;
      padding: 20px;
      text-align: right;
      vertical-align: baseline;
      a {
        color: #0069ca;
      }
      img {
        width: 30px;
        height: 30px;
        object-fit: cover;
        cursor: pointer;
        vertical-align: middle;
      }
    }
    // 文章内容区域
    /deep/.post_content {
      p {
        text-indent: 30px;
        img {
          display: block;
          max-width: 700px;
          max-height: 500px;
          object-fit: contain;
          margin: 10px 0px;
        }
      }
    }
    //分享按钮区域
    .post_crtl {
      padding: 50px 0 30px;
      display: flex;
      justify-content: center;
      .post_crtl_item {
        margin: 0 20px;
        text-align: center;
        cursor: pointer;
        span {
          font-size: 28px;
          color: orange;
        }
        p {
          margin-top: 5px;
          font-size: 14px;
          color: #999;
        }
      }
    }
    // 评论区域
    .cmt_wrapper {
      .cmt_reply_noUser {
        height: 120px;
        text-align: center;
        border: 1px solid #e0e0e0;
        line-height: 120px;
        margin-bottom: 10px;
        a {
          color: #0069ca;
        }
      }
      .cmt_title {
        font-weight: 400;
        font-size: 18px;
        margin-bottom: 20px;
      }
      .cmt_input {
        margin-bottom: 10px;
        /deep/ .el-textarea__inner {
          resize: none;
          min-height: 33px;
        }
      }
      // 上传文件和发表按钮组件
      .cmt_input_ctrls {
        margin-bottom: 30px;
        display: flex;
        justify-content: space-between;
        /deep/ .el-upload {
          width: 112px;
          height: 112px;
          line-height: 112px;
        }
        /deep/.el-upload-list__item {
          width: 112px;
          height: 112px;
        }
        /deep/ .el-avatar--square {
          width: 112px;
          height: 112px;
          img {
            width: 100%;
          }
        }
      }
      // 评论组件
      .cmt_empty {
        color: #999;
        font-size: 14px;
        text-align: center;
        padding: 30px 0;
        border: 1px dashed #ddd;
      }
      .cmt_list {
        border: 1px solid #ddd;
      }
    }
    // 分页组件
    .page {
      margin-top: 10px;
      text-align: center;
    }
  }
}
</style>